import { onBeforeUnmount, onMounted, ref } from "vue";

type ResizeType = {
	w?: number;
	h?: number;
	fullScreen?: boolean; //是否全屏
	delay?: number; //防抖
};

//默认适配的宽高
export const BASE_WIDTH = 1920;
export const BASE_HEIGHT = 1080;

/**
 * 自适应布局
 * @param options
 * @returns
 */
export const useResize = (options: ResizeType = {}): any => {
	const {
		w = BASE_WIDTH,
		h = BASE_HEIGHT,
		fullScreen = false,
		delay = 100,
	} = options;

	const screenRef = ref<HTMLElement>();
	const scale = ref(1);

	/**
	 * 调整尺寸
	 */
	function resize() {
		//获取视口宽高
		let clientWidth = document.documentElement.clientWidth;
		let clientHeight = document.documentElement.clientHeight;

		const scaleW = clientWidth / w;
		const scaleH = clientHeight / h;
		//获取最小的缩放比例
		scale.value = Math.min(scaleW, scaleH)

		if (fullScreen) {
			//不在乎失真  直接全屏
			screenRef.value!.style.transform = `scale(${scaleW}, ${scaleH})`;
		} else {
			//等比缩放
			screenRef.value!.style.transform = `scale(${scale.value})`;

			//设置居中
			screenRef.value!.style.left = `${(clientWidth - w * scale.value) / 2}px`;
			screenRef.value!.style.top = `${(clientHeight - h * scale.value) / 2}px`;
		}
	}

	onMounted(() => {
		if (screenRef.value) {
			resize();
			window.addEventListener("resize", () => {
				debounce(resize, delay)();
			});
		}
	});

	onBeforeUnmount(() => {
		window.removeEventListener("resize", () => {
			debounce(resize, delay)();
		});
	});


	return {
		screenRef,
		scale,
	};
};

/**
 * 防抖函数
 * @param fn 最终要执行的函数
 * @param delay 防抖延迟时间
 * @returns
 */
function debounce(fn: Function, delay: number = 100) {
	let timer: NodeJS.Timeout | null = null;
	return (...args: any[]) => {
		if (timer) {
			clearTimeout(timer);
		}
		timer = setTimeout(
			() => {
				typeof fn === "function" && fn.apply(null, args);
			},
			delay > 0 ? delay : 100
		);
	};
}
